package com.yjx.gulimall.product.service.impl;

import com.yjx.gulimall.common.constant.product.AttrConstant;
import com.yjx.gulimall.product.dao.AttrAttrgroupRelationDao;
import com.yjx.gulimall.product.dao.AttrGroupDao;
import com.yjx.gulimall.product.entity.AttrAttrgroupRelationEntity;
import com.yjx.gulimall.product.entity.AttrGroupEntity;
import com.yjx.gulimall.product.entity.CategoryEntity;
import com.yjx.gulimall.product.service.AttrAttrgroupRelationService;
import com.yjx.gulimall.product.service.CategoryService;
import com.yjx.gulimall.common.vo.product.AttrAttrgroupRelationEntityVO;
import com.yjx.gulimall.common.vo.product.AttrResponseVO;
import com.yjx.gulimall.common.vo.product.AttrVO;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yjx.gulimall.common.utils.PageUtils;
import com.yjx.gulimall.common.utils.Query;

import com.yjx.gulimall.product.dao.AttrDao;
import com.yjx.gulimall.product.entity.AttrEntity;
import com.yjx.gulimall.product.service.AttrService;
import org.springframework.util.CollectionUtils;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {

    @Autowired
    private AttrAttrgroupRelationService attrAttrgroupRelationService;

    @Autowired
    private AttrAttrgroupRelationDao attrAttrgroupRelationDao;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private AttrGroupDao attrGroupDao;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }



    /**
     * @param attr
     */
    @Override
    public void saveAttr(AttrVO attr) {

        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr, attrEntity);
        //保存基本属性
        this.save(attrEntity);
        Long attrId = attrEntity.getAttrId();

        AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();
        attrAttrgroupRelationEntity.setAttrId(attrId);
        attrAttrgroupRelationEntity.setAttrGroupId(attr.getAttrGroupId());
        attrAttrgroupRelationEntity.setAttrSort(0);
        attrAttrgroupRelationService.save(attrAttrgroupRelationEntity);

    }

    /**
     * 规格参数基本属性
     *
     * @param params
     * @param catelogId
     * @return
     */
    @Override
    public PageUtils queryBasePage(Map<String, Object> params, Long catelogId,String type) {

        QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<AttrEntity>().eq("attr_type","base".equalsIgnoreCase(type) ?
                AttrConstant.AttrEnum.ATTR_TYPE_BASE.getCode() :
                AttrConstant.AttrEnum.ATTR_TYPE_SALE.getCode());

        if (catelogId != 0) {
            queryWrapper = queryWrapper.and(obj -> {
                obj.eq("catelog_id", catelogId);
            });
        }
        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)) {
            queryWrapper = queryWrapper.and(obj -> {
                obj.like("attr_name", key).or().like("attr_id", key);
            });
        }
        //分页查询
        IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(params), queryWrapper);

        PageUtils pageUtils = new PageUtils(page);

        List<AttrResponseVO> attrResponseVOList = page.getRecords().stream().map(attrEntity -> {
            AttrResponseVO attrResponseVO = new AttrResponseVO();
            BeanUtils.copyProperties(attrEntity, attrResponseVO);

            //查询分类分类名称
            CategoryEntity categoryEntity = categoryService.getById(attrEntity.getCatelogId());
            if (categoryEntity != null) {
                attrResponseVO.setCatelogName(categoryEntity.getName());
            }

            AttrAttrgroupRelationEntity relationEntity = attrAttrgroupRelationService.getRelationEntityByAttrId(attrEntity.getAttrId());
            if (relationEntity != null && relationEntity.getAttrGroupId() != null) {
                AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(relationEntity.getAttrGroupId());
                attrResponseVO.setGroupName(attrGroupEntity.getAttrGroupName());
            }


            return attrResponseVO;
        }).collect(Collectors.toList());

        pageUtils.setList(attrResponseVOList);
        return pageUtils;
    }

    @Override
    public AttrResponseVO getAttrById(Long attrId) {

        AttrResponseVO attrResponseVO = new AttrResponseVO();
        AttrEntity attrEntity = this.getById(attrId);
        BeanUtils.copyProperties(attrEntity, attrResponseVO);
        Long[] catelogPath = categoryService.findCatelogPath(attrEntity.getCatelogId());
        attrResponseVO.setCatelogPath(catelogPath);

        //获取属性组
        AttrAttrgroupRelationEntity relationEntity = attrAttrgroupRelationService.getRelationEntityByAttrId(attrId);
        if (relationEntity != null && relationEntity.getAttrGroupId() != null) {
            AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(relationEntity.getAttrGroupId());
            attrResponseVO.setAttrGroupId(relationEntity.getAttrGroupId());
            attrResponseVO.setGroupName(attrGroupEntity.getAttrGroupName());
        }

        return attrResponseVO;
    }

    /**
     * 获取当前分组没有关联的所有属性
     * 1、条件是当前分类下的所有属性分组
     * 2、没有被分组关联的属性【包括自己关联的】
     *
     * @param params
     * @param attrGroupId
     * @return
     */
    @Override
    public PageUtils getNoRelationAttr(Map<String, Object> params, Long attrGroupId) {
        // 1、当前分组只能关联所属分类下的所有属性
        // 先查出分类ID
        AttrGroupEntity groupEntity = attrGroupDao.selectById(attrGroupId);
        Long catelogId = groupEntity.getCatelogId();
        // 2、只能显示当前分类下没有被关联的属性
        // 2.1）查出所属分类下的所有分组
        List<AttrGroupEntity> groups = attrGroupDao.selectList(new QueryWrapper<AttrGroupEntity>().eq("catelog_id", catelogId));
        List<Long> groupIds = groups.stream().map((item) -> {
            return item.getAttrGroupId();
        }).collect(Collectors.toList());
        // 2.2）查出这些分组已经关联的属性
        List<AttrAttrgroupRelationEntity> relationEntities = new ArrayList<AttrAttrgroupRelationEntity>();
        if (!CollectionUtils.isEmpty(groupIds)) {
            relationEntities = attrAttrgroupRelationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().in("attr_group_id", groupIds));
        }
        List<Long> attrIds = relationEntities.stream().map((item) -> {
            return item.getAttrId();
        }).collect(Collectors.toList());

        // 2.3）从当前分类下的所有属性里 剔除已关联的属性
        QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<AttrEntity>().eq("catelog_id", catelogId).eq("attr_type", AttrConstant.AttrEnum.ATTR_TYPE_BASE.getCode());
        if (!CollectionUtils.isEmpty(attrIds)) {
            queryWrapper.notIn("attr_id", attrIds);
        }
        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)) {
            queryWrapper.and((w) -> {
                w.eq("attr_id", key).or().like("attr_name", key);
            });
        }
        IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(params), queryWrapper);
        PageUtils pageUtils = new PageUtils(page);
        return pageUtils;
    }

    @Override
    public void deleteAttRelation(AttrAttrgroupRelationEntityVO[] relationEntityArrayVO) {

        List<AttrAttrgroupRelationEntity> relationList = Arrays.stream(relationEntityArrayVO).map(obj -> {
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();
            attrAttrgroupRelationEntity.setAttrGroupId(obj.getAttrGroupId());
            attrAttrgroupRelationEntity.setAttrId(obj.getAttrId());
            return attrAttrgroupRelationEntity;
        }).collect(Collectors.toList());

        attrAttrgroupRelationDao.deleteBatchRelation(relationList);

    }

    /**
     *
     * @param relationEntityVOS
     */
    @Override
    public void saveAttrRelation(AttrAttrgroupRelationEntityVO[] relationEntityVOS) {
        List<AttrAttrgroupRelationEntity> relationList = Arrays.stream(relationEntityVOS).map(obj -> {
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();
            attrAttrgroupRelationEntity.setAttrGroupId(obj.getAttrGroupId());
            attrAttrgroupRelationEntity.setAttrId(obj.getAttrId());
            return attrAttrgroupRelationEntity;
        }).collect(Collectors.toList());

        attrAttrgroupRelationDao.saveBatchRelation(relationList);
    }

    @Override
    public void updateByAttrVoId(AttrVO attr) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr,attrEntity);
        this.updateById(attrEntity);

         //如果分组id 不为空，则绑定分组id
        if(attr.getAttrGroupId() != null){
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();
            attrAttrgroupRelationEntity.setAttrGroupId(attr.getAttrGroupId());
            attrAttrgroupRelationEntity.setAttrId(attr.getAttrId());
             boolean updateFlag = attrAttrgroupRelationService.update(attrAttrgroupRelationEntity, new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attr.getAttrId()));
             if(!updateFlag){
                 attrAttrgroupRelationService.save(attrAttrgroupRelationEntity);
             }
        }
    }

    @Override
    public List<AttrEntity> getBatchByIds(List<Long> ids) {
        return this.baseMapper.selectBatchIds(ids);
    }


    /**
     * 获取所有的关联属性
     *
     * @param attrGroupId
     * @return
     */
    @Override
    public List<AttrEntity> getByAttrGroupId(Long attrGroupId) {

        List<Long> attrIdList = attrAttrgroupRelationDao.getAttrIdsByAttrGroupId(attrGroupId);

        if (attrIdList == null || attrIdList.isEmpty()) {
            return new ArrayList<>();
        }

        List<AttrEntity> attrEntities = baseMapper.selectBatchIds(attrIdList);

        return attrEntities;
    }


}